package judesart.app.client.ga;

import judesart.app.client.ApplicationProperties;

import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.user.client.Timer;

public class Tracker {
	
	private static Boolean enabled;
	
	public static void trackGoogleAnalytics(final String pageName){
		if (setEnabled()){
			if (!enabled){
				Log.debug("Tracker : Skiping track page : [" + pageName + "]. Not in production.");
				return;
			}else{
				trackGoogleAnalyticsJS(pageName);
				Log.debug("Tracked : [" + pageName + "]");
			}
		}else{
			Log.debug("Tracker : Application properties not set will try again in the future. Track page : [" + pageName + "].");
			Timer t = new Timer(){
				@Override
				public void run() {
					trackGoogleAnalytics(pageName);
					this.cancel();
				}
			};
			t.schedule(2000);
		}
	}
	
	private static boolean setEnabled(){
		if (enabled != null)
			return true;
		if (ApplicationProperties.isInitialized()){
			enabled = ApplicationProperties.isProduction() && !ApplicationProperties.getVersion().startsWith("test");
			return true;
		}
		return false;
	}
	
	private static native void trackGoogleAnalyticsJS(String pageName) /*-{
    
    try {
    	$wnd._gaq.push(['_setAccount', 'UA-20338152-1']);
    	$wnd._gaq.push(['_trackPageview', pageName]);
    } catch(err) {
      alert('FAILURE: to send in event to google analytics: ' + err);
    }
    
    }-*/;

}
